#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2 as urllib
import simplejson as json
import sys
import os
import MySQLdb

KEY = "b3d45ad9888f8b1f133b5e4a5a12c4c3"
QUERY = sys.argv[1]

def createUrl(key, lang_from, lang_to, query):
    url = "http://api.seslisozluk.com/?key=%s&lang_from=%s&lang_to=%s&query=%s" %(key, lang_from, lang_to, query)
    return url

def getJSON(url):
    page = urllib.urlopen(url)
    page = page.read()
    return page

def getQuery(obj):
    return obj["query"]

def getLangFrom(obj):
    return obj["lang_from"]

def getLangTo(obj):
    return obj["lang_to"]

def getTranslations(obj):
    return obj["translations"]

def getPronunciation(obj):
    return obj("pronunciation")

def save(word, translation):
    conn = MySQLdb.connect(host="localhost", user="pardus", passwd="", db="spanish")
    cursor = conn.cursor()
    query = "insert into words (word, translation) values ('%s', '%s')" %(word, translation)
    cursor.execute(query)
    conn.commit()
    conn.close()

trans = ("tr", "en", "es")

template = ""
template = template + QUERY + " "
for t in trans:
    obj = json.loads(getJSON(createUrl(KEY,"es", t, QUERY)))
    vocs = getTranslations(obj)
    lang_pair = "es-%s" %t
    template = template + "| "
    for v in vocs:
        if v["lang_pair"] == lang_pair:
            template = template + v["translation"] + ", "

template = template[:-4].capitalize()
template = unicode(template)
print template
q = raw_input("Do you want ta save it?")
if q == "yes":
    save(QUERY, template)
else:
    print "get out."

